import moment from 'moment'
import html2canvas from 'html2canvas'

moment.locale('zh_CN')
var CryptoJS = require('crypto-js');

export function deepCopy(obj, cache = []) {
  // just return if obj is immutable value
  if (obj === null || typeof obj !== 'object') {
    return obj
  }
}
export default {
  showLevel: function (grace, level, levelText) {
    for (let i = 0; i < level.length; i++) {
      if (grace > level[i]) {
        return levelText[i];
      }
    }
    //如果不存在，那么就是分数很低，返回最后一个
    return levelText[levelText.length - 1]
  },
  deepGet: function (object, path, defaultValue) {
    return (!Array.isArray(path) ? path.replace(/\[/g, '.').replace(/\]/g, '').split('.') : path)
      .reduce((o, k) => (o || {})[k], object) || defaultValue;
  },
  initReEdit: function () {
    setTimeout(function () {
      //重新编辑公式
      $($(document).find('iframe').contents().find('body.view')).on('click', '.kfformula', function () {
        let viewArr = $(document).find('iframe').contents().find('body.view');
        for (var i = 0; i < viewArr.length; i++) {
          if (viewArr[i] === $(this).closest('body.view')[0]) {
            $($('.edui-for-插入kityformula')[i]).find('.edui-default').click();
          }
        }
      });
      //重新编辑latex
      $($(document).find('iframe').contents().find('body.view')).on('click', '.latex', function () {
        let viewArr = $(document).find('iframe').contents().find('body.view');
        for (var i = 0; i < viewArr.length; i++) {
          if (viewArr[i] === $(this).closest('body.view')[0]) {
            $($('.edui-for-解析latex')[i]).find('.edui-default').click();
          }
        }
      });
      //重新编辑化学公式
      $($(document).find('iframe').contents().find('body.view')).on('click', '.chem-plugin', function () {
        let viewArr = $(document).find('iframe').contents().find('body.view');
        sessionStorage.setItem('smiles', $(this).data("latex"));
        window.smiles = $(this).data("latex");
        for (var i = 0; i < viewArr.length; i++) {
          if (viewArr[i] === $(this).closest('body.view')[0]) {
            $($('.edui-for-插入chem')[i]).find('.edui-default').click();
          }
        }
      });

    }, 1000)
  },
  convertImgToBase64: function (url, callback, isLatex, outputFormat) {
    var canvas = document.createElement('CANVAS'),
      ctx = canvas.getContext('2d'),
      img = new Image;
    img.crossOrigin = 'Anonymous';
    img.onload = function () {
      canvas.height = img.height;
      canvas.width = img.width;
      ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, img.width, img.height);
      var dataURL = canvas.toDataURL(outputFormat || 'image/png');
      callback.call(this, dataURL);
      canvas = null;
    };
    img.src = url;
  },
  htmlToImg(id, cb) {
    let content_html = document.getElementById(id);　　　　//要转化的div
    let width = content_html.offsetWidth;
    let height = content_html.offsetHeight;
    let offsetTop = content_html.offsetTop;
    let canvas = document.createElement("canvas");
    let context = canvas.getContext('2d');
    let scaleBy = Math.ceil(window.devicePixelRatio) + 3;
    canvas.width = width * scaleBy;
    canvas.height = (height + offsetTop) * scaleBy;
    context.scale(scaleBy, scaleBy);
    var opts = {
      allowTaint: true,//允许加载跨域的图片
      tainttest: true, //检测每张图片都已经加载完成
      scale: scaleBy, // 添加的scale 参数
      canvas: canvas, //自定义 canvas
      logging: false, //日志开关，发布的时候记得改成false
      width: width, //dom 原始宽度
      height: height //dom 原始高度
    };
    html2canvas(content_html, opts).then((canvas) => {
      canvas.style.width = width + "px";
      canvas.style.height = height + "px";
      try {
        cb(canvas.toDataURL("image/jpeg"))
      } catch (err) {
        alert(err)
      }
    });
  },
  base64encode: function (str) {
    let img = new Image;
    img.src = str;
    img.onload = function () {
      console.log(img)
      let fr = new FileReader();
      console.log(fr.readAsDataURL(img))
    }
    var _str = CryptoJS.enc.Utf8.parse(str);
    var _base64 = CryptoJS.enc.Base64.stringify(_str);
    console.log(_base64);
    return _base64;
  },
  mapTree: function (arr) {
    let lastArr = [];
    function mapTurn(arr) {
      arr.map((item => {
        if (item.childrenNodes) {
          lastArr.push({ id: item.knowledgeNodeId, pId: item.parentKnowledgeNodeId, name: item.name ? item.name : '新知识点', status: item.editStatus, sequence: item.sequence, font: { 'color': 'red' } });
          mapTurn(item.childrenNodes);
        } else {
          lastArr.push({ id: item.knowledgeNodeId, pId: item.parentKnowledgeNodeId, name: item.name ? item.name : '新知识点', status: item.editStatus, sequence: item.sequence, font: { 'color': 'red' } });
        };
      }))
    };
    mapTurn(arr);
    return lastArr;
  },
  mapReportTree: function (arr) {
    let lastArr = [];
    function mapReportTurn(arr) {
      arr.map((item => {
        if (item.childrenNodes) {
          lastArr.push(Object.assign({}, item, { id: item.knowledgeNodeId, pId: item.parentKnowledgeNodeId, name: item.name ? item.name : '新知识点' }));
          mapReportTurn(item.childrenNodes);
        } else {
          lastArr.push(Object.assign({}, item, { id: item.knowledgeNodeId, pId: item.parentKnowledgeNodeId, name: item.name ? item.name : '新知识点' }));
        };
      }))
    };
    mapReportTurn(arr);
    return lastArr;
  },
  getQueryString: function (name) {
    var r = window.location.search.substr(1).match(new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"));
    if (r) {
      return r[2];
    }
    return null;
  },
  formatTime: function (time, format) {
    if (!time) return "";
    if (typeof time == "string") {
      time = parseInt(time, 10);
    }
    return moment(time).format(format || 'YYYY-MM-DD H:mm:ss')
  },
  formatDate: function (time, format) {
    if (!time) return "";
    if (typeof time == "string") {
      time = parseInt(time, 10);
    }
    return moment(time).format(format || 'YYYY-MM-DD')
  },
  firstDayOfMonth: function () {
    return moment().startOf('month');
  },
  endDayOfMonth: function () {
    return moment().endOf('month')
  },

  currentYear: function () {
    return moment().year()
  },

  currentMonth: function () {
    return moment().month() + 1
  },

  formatNumber: function (val, fixed) {
    return parseFloat(val).toFixed(fixed)
  },

  toNumber: function (val) {
    return Number(val)
  },
  isEmptyObject: function (e) {
    var t;
    for (t in e)
      return !1;
    return !0
  },
  SectionToChinese: function (section) {
    var chnNumChar = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
    var chnUnitSection = ["", "万", "亿", "万亿", "亿亿"];
    var chnUnitChar = ["", "十", "百", "千"];
    var strIns = '', chnStr = '';
    var unitPos = 0;
    var zero = true;
    while (section > 0) {
      var v = section % 10;
      if (v === 0) {
        if (!zero) {
          zero = true;
          chnStr = chnNumChar[v] + chnStr;
        }
      } else {
        zero = false;
        strIns = chnNumChar[v];
        strIns += chnUnitChar[unitPos];
        chnStr = strIns + chnStr;
      }
      unitPos++;
      section = Math.floor(section / 10);
    }
    return chnStr;
  },
  install: function (Vue) {
    Vue.filter('formatDate', this.formatDate)
    Vue.filter('formatTime', this.formatTime)
    Vue.filter('formatNumber', this.formatNumber)
    Vue.filter('toNumber', this.toNumber)
    Vue.filter('deepGet', this.deepGet)
    Vue.filter('SectionToChinese', this.SectionToChinese)

    var isEmptyObject = this.isEmptyObject
    Vue.mixin({
      methods: {
        isEmptyObject: isEmptyObject,
        deepGet: this.deepGet
      }
    })
  }
}
